import { makeAutoObservable } from 'mobx';
import { Prompt, PromptFormValues } from './promptTypes';
import { getPromptList, createPrompt, updatePrompt, getInfo, deletePrompt } from '../../../../apis/backhub/prompt';
import { message } from 'antd';

class PromptStore {
  prompts: Prompt[] = [];
  modalVisible = false; // 弹窗显示状态
  editingPrompt: Prompt | undefined = undefined; // 当前编辑的提示词，undefined表示新建
  loading = false;

  constructor() {
    makeAutoObservable(this);
  }

  // 获取提示词列表
  fetchPrompts = async () => {
    this.loading = true;
    try {
      const response = await getPromptList();
      this.prompts = (response as any)?.data;
    } catch (error) {
      console.error('获取提示词列表失败:', error);
    } finally {
      this.loading = false;
    }
  };

  // 显示创建弹窗
  showCreateModal = () => {
    this.editingPrompt = undefined;
    this.modalVisible = true;
  };

  // 显示编辑弹窗
  showEditModal = (prompt: Prompt) => {
    this.getPrompt(prompt.id);
    this.modalVisible = true;
  };

  // 隐藏弹窗
  hideModal = () => {
    this.modalVisible = false;
    this.editingPrompt = undefined;
  };

  //获取模型
  getPrompt = async (id: string) => {
    try {
      this.loading = true;
      const response = await getInfo(id);
      this.editingPrompt = (response as any).data;
      return this.editingPrompt; // 返回获取到的用户数据
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  // 保存提示词
  savePrompt = async (values: PromptFormValues) => {
    try {
      values.variables = JSON.stringify(values.variablesArray);
      if (this.editingPrompt && this.editingPrompt.id) {
        const response = await updatePrompt(this.editingPrompt.id, values);
        if((response as any)?.status){
          message.success('保存成功');
        }
      } else {
        await createPrompt(values);
      }
      this.hideModal();
      this.fetchPrompts();
    } catch (error) {
      console.error('保存提示词失败:', error);
    }
  };

  // 删除提示词
  deletePrompt = async (id: string) => {
    try {
      const response = await deletePrompt(id);
      if((response as any)?.status){
        message.success('删除成功');
      }
      this.fetchPrompts();
    } catch (error) {
      console.error('删除提示词失败:', error);
    }
  };
}

export const promptStore = new PromptStore();